﻿using Dm.Config;
using NLog;
using SnakeShop.IRepository.UnitOfWork;
using SnakeShop.Loging;
using SqlSugar;
using SqlSugar.IOC;
using LogLevel = NLog.LogLevel;

namespace SnakeShop.Repository.UnitOfWork
{
    public class UnitOfWork: IUnitOfWork
    {

        private readonly ISqlSugarClient _sqlSugarClient;

        public UnitOfWork()
        {
            _sqlSugarClient = DbScoped.SugarScope;
        }


        /// <summary>
        /// 获取DB， 保证唯一性
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public SqlSugarScope GetDbClient()
        {
            return _sqlSugarClient as SqlSugarScope;
        }

        public void BeginTran()
        {
            GetDbClient().BeginTran();
        }

        public void CommitTran()
        {
            try
            {
                GetDbClient().CommitTran();
            }
            catch (Exception ex)
            {
                GetDbClient().RollbackTran();
                NLogUtil.WriteFileLog(LogLevel.Error, LogType.Web, "事务提交异常", "事务提交异常",new Exception("事务提交异常", ex));
            }
        }

        public void RollbackTran()
        {
            GetDbClient().RollbackTran();
        }
    }
}
